import 'dart:ffi';
import 'dart:io';

import 'package:easy_chat_app/commons/utils/PlatformUtils.dart';
import 'package:logger/logger.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:sqlite3/open.dart';

void ffiInit() {
  open.overrideFor(
    OperatingSystem.windows,
    () => DynamicLibrary.open('data/flutter_assets/dynamic-lib/sqlite3.dll'),
  );
}

class DBUtils {
  static final Logger logger = Logger();

  static Database? _db;

  static Future<void> initDB() async {
    if (Platform.isWindows) {
      Directory documentDirectory = await getApplicationDocumentsDirectory();
      // 桌面环境初始化sqflite
      final dbFactory = createDatabaseFactoryFfi(ffiInit: ffiInit);
      _db = await dbFactory
          .openDatabase("${documentDirectory.path}/easy_chat/easy_chat.db");
    }
    if (PlatformUtils.isMobile()) {
      _db = await openDatabase("easy_chat.db");
    }
    _initMessageTable(_db!);
  }

  static Database getDatabaseInstance() {
    return _db!;
  }

  static Database getDB() {
    return getDatabaseInstance();
  }

  static _initMessageTable(Database database) async {
    logger.i("初始化数据库 start...");
    await database.execute("""
    create table if not exists local_conversation
    (
        id             INTEGER not null
            primary key,
        uid1           INTEGER not null,
        uid2           INTEGER,
        updateTime     INTEGER not null,
        newestMsg      TEXT,
        newestMsgType  INTEGER,
        unreadMsgCount INTEGER default 0 not null,
        type           INTEGER,
        chatGroupId    INTEGER
    );
    """);
    await database.execute("""
    create unique index if not exists conversation_uid1_uid2_uindex
        on local_conversation (uid1, uid2);
    """);
    await database.execute("""
    create unique index if not exists local_conversation_uid1_chatGroupId_uindex
        on local_conversation (uid1, chatGroupId);
    """);
    await database.execute("""
    create index if not exists local_conversation_updateTime_index
        on local_conversation (updateTime);
    """);

    await database.execute("""
    create table if not exists local_message
    (
        localMsgId     INTEGER
            constraint message_pk
                primary key autoincrement,
        conversationId INTEGER not null,
        serverMsgId    INTEGER,
        sourceUserId   INTEGER not null,
        targetUserId   INTEGER,
        chatGroupId    INTEGER,
        chatType       INTEGER not null,
        messageType    INTEGER not null,
        message        TEXT,
        sendTime       INTEGER not null,
        status         INTEGER not null,
        messageSource  INTEGER not null,
        readState      INTEGER default 0 not null
    );
    """);
    await database.execute("""
        create unique index if not exists local_message_serverMsgId_uindex on local_message (serverMsgId);
    """);
    await database.execute("""
        create index if not exists local_message_conversationId_localMsgId_index on local_message (conversationId, localMsgId);
    """);
    await database.execute("""
        create index if not exists local_message_conversationId_readState_index
            on local_message (conversationId, readState);
    """);
    logger.i("初始化数据库 success...");
  }
}
